package com.example.testmvp;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.testmvp.model.User;
import com.example.testmvp.presener.LoginPresener;
import com.example.testmvp.presener.LoginPresenerImpl;
import com.example.testmvp.view.LoginView;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.youth.banner.Banner;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements LoginView {

    @Bind(R.id.account)
    EditText account;
    @Bind(R.id.pwd)
    EditText pwd;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.pb)
    ProgressBar pb;
    @Bind(R.id.banner)
    Banner banner;
    @Bind(R.id.toolbar_new)
    Toolbar toolbarNew;
    @Bind(R.id.coll_tool_var)
    CollapsingToolbarLayout collToolVar;
    @Bind(R.id.root)
    CoordinatorLayout root;
    @Bind(R.id.app_bar)
    AppBarLayout appBar;
    @Bind(R.id.ll)
    LinearLayout ll;
    @Bind(R.id.flexbox_layout)
    FlexboxLayout flexboxLayout;
    @Bind(R.id.recycle_view)
    RecyclerView recycleView;


    private FlexBoxAdapter adapter;
    private LoginPresener presenter;

    private enum CollapsingToolbarLayoutState {
        EXPANDED,
        COLLAPSED,
        INTERNEDIATE
    }

    private CollapsingToolbarLayoutState state;

    //设置图片资源:url或本地资源


    String[] images = new String[]{
            "http://218.192.170.132/BS80.jpg",
            "http://img.zcool.cn/community/0166c756e1427432f875520f7cc838.jpg",
            "http://img.zcool.cn/community/018fdb56e1428632f875520f7b67cb.jpg",
            "http://img.zcool.cn/community/01c8dc56e1428e6ac72531cbaa5f2c.jpg",
            "http://img.zcool.cn/community/01fda356640b706ac725b2c8b99b08.jpg",
            "http://img.zcool.cn/community/01fd2756e142716ac72531cbf8bbbf.jpg",
            "http://img.zcool.cn/community/0114a856640b6d32f87545731c076a.jpg"};


    //设置图片标题:自动对应
    String[] titles = new String[]{"十大星级品牌联盟，全场2折起", "全场2折起", "十大星级品牌联盟", "嗨购5折不要停", "12趁现在", "嗨购5折不要停，12.12趁现在", "实打实大顶顶顶顶"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        Drawable windowBackground = getWindow().getDecorView().getBackground();

        //初始化Banner控件
        initBanner();

        //初始化AppBar滑动控件
        initAppBar();

        //初始化代码添加FlexBoxLayout的Item
        initAddItem();

        initRecyAdapter();

        presenter = new LoginPresenerImpl(this);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User user = new User();
                user.setPassword(pwd.getText().toString());
                user.setUsername(account.getText().toString());
                presenter.validateCredentials(user);
            }
        });
    }

    private void initRecyAdapter() {
        adapter = new FlexBoxAdapter(this, images);
        FlexboxLayoutManager manager = new FlexboxLayoutManager();
        //设置主轴排列方式
        manager.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        manager.setFlexWrap(FlexWrap.WRAP);
        recycleView.setLayoutManager(manager);
        recycleView.setItemAnimator(new DefaultItemAnimator());
        recycleView.setAdapter(adapter);
    }

    private void initAddItem() {
        TextView textView = new TextView(this);
        textView.setBackground(getResources().getDrawable(R.drawable.label_bg_shape));
        textView.setText("Test  Label");
        textView.setGravity(Gravity.CENTER);
        textView.setPadding(30, 30, 30, 30);
        textView.setTextColor(getResources().getColor(R.color.colorAccent));

        flexboxLayout.addView(textView);
        //通过FlexboxLayout.LayoutParams 设置子元素支持的属性
    }

    private void initAppBar() {
        appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                        collToolVar.setTitle("EXPANDED");//设置title为EXPANDED
                    }
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                        collToolVar.setTitle("");//设置title不显示
                        ll.setVisibility(View.VISIBLE);//隐藏播放按钮
                        state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                    }
                } else {
                    if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                        if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                            ll.setVisibility(View.GONE);//由折叠变为中间状态时隐藏播放按钮
                        }
                        collToolVar.setTitle("INTERNEDIATE");//设置title为INTERNEDIATE
                        state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                    }
                }
            }
        });
    }

    private void initBanner() {


        //设置样式,默认为:Banner.NOT_INDICATOR(不显示指示器和标题)
        //可选样式如下:
        //1. Banner.CIRCLE_INDICATOR    显示圆形指示器
        //2. Banner.NUM_INDICATOR    显示数字指示器
        //3. Banner.NUM_INDICATOR_TITLE    显示数字指示器和标题
        //4. Banner.CIRCLE_INDICATOR_TITLE    显示圆形指示器和标题
        banner.setBannerStyle(Banner.CIRCLE_INDICATOR_TITLE);

        //设置轮播样式（没有标题默认为右边,有标题时默认左边）
        //可选样式:
        //Banner.LEFT    指示器居左
        //Banner.CENTER    指示器居中
        //Banner.RIGHT    指示器居右
        banner.setIndicatorGravity(Banner.RIGHT);

        //设置轮播要显示的标题和图片对应（如果不传默认不显示标题）
        banner.setBannerTitle(titles);

        //设置是否自动轮播（不设置则默认自动）
        banner.isAutoPlay(true);

        //设置轮播图片间隔时间（不设置默认为2000）
        banner.setDelayTime(1000);

        //设置图片资源:可选图片网址/资源文件，默认用Glide加载,也可自定义图片的加载框架
        //所有设置参数方法都放在此方法之前执行
        //banner.setImages(images);

        banner.setImages(images, new Banner.OnLoadImageListener() {
            @Override
            public void OnLoadImage(ImageView view, Object url) {
                System.out.println("加载中...");

                Glide.with(MainActivity.this).load(url).centerCrop().into(view);

                System.out.println("加载完");
            }
        });

        //设置点击事件，下标是从1开始
        banner.setOnBannerClickListener(new Banner.OnBannerClickListener() {
            @Override
            public void OnBannerClick(View view, int position) {
                Toast.makeText(getApplicationContext(), "你点击了：" + position, Toast.LENGTH_LONG).show();
            }
        });

    }

    @Override
    public void showProgress() {
        pb.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        pb.setVisibility(View.GONE);
    }

    @Override
    public void setUsernameError() {
        account.setError("用户名为空");
    }

    @Override
    public void setPasswordError() {
        pwd.setError("密码为空");
    }

    @Override
    public void showSuccess() {
        pb.setVisibility(View.GONE);
        Toast.makeText(this, "login success", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        presenter.onDestroy();
        super.onDestroy();
    }
}
